<template>
  <div class="tank-dialog" :style="showAnimation">
    <div class="back" @click="hide"></div>
    <div class="front">
      <div class="modal-header">
        <div class="mdoal-title">工艺槽信息</div>
        <Button type="primary" icon="md-add" @click="handleAdd"
          >添加槽信息</Button
        >
      </div>
      <Table :columns="columns" :data="tableData" border>
        <template slot-scope="{ row }" slot="tankName">
          <Input v-model="row.tankName" disabled placeholder="请输入槽名称" />
        </template>
        <template slot-scope="{ row }" slot="tankNumber">
          <Input v-model="row.tankNumber" placeholder="请输入物理槽号" />
        </template>
        <template slot-scope="{ index }" slot="action">
          <Button type="error" size="small" @click="handleDelete(index)"
            >删除</Button
          >
        </template>
      </Table>
      <div class="modal-footer">
        <div class="modal-button" data-text="确定" @click="handleSubmit"></div>
        <div class="modal-button" data-text="取消" @click="handleCancel"></div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Node,
  ProcessNodeData,
  T_srv,
  TankData,
  Tsrv,
  ifs,
  ts,
  vue
} from './config';

interface config {
  // modalTitle?: string;
  // modalSize?: Array<number>;
  // config?: any;
  node: Node;
  craftType: number;
}

@T_srv.comp
export default class cTankDialog extends vue {
  @T_srv.prop() config: config;

  @T_srv.prop() id: string;

  private showAnimation: any = {};

  private currentNode: Node | null = null;

  private processId: string = '';

  private parentId: string = '';

  private tableData: TankData[] = [];

  private originData: TankData[] = [];

  private columns = [
    {
      title: '槽名称',
      slot: 'tankName',
      key: 'tankName'
    },
    // {
    //   title: '物理槽号',
    //   slot: 'tankNumber',
    //   key: 'tankNumber'
    // },
    {
      title: '操作',
      slot: 'action',
      width: 100,
      align: 'center'
    }
  ];

  created() {
    this.init();
  }

  private init(): void {
    this.initData();
    this.show();
  }

  private initData(): void {
    const node = this.config.node;
    this.currentNode = node;
    const data = node.getData() as ProcessNodeData;
    this.processId = data.processId;
    this.parentId = data.id;
    const tankData = Array.isArray(data.tankData) ? data.tankData : [];
    this.tableData = JSON.parse(JSON.stringify(tankData));
    this.originData = JSON.parse(JSON.stringify(tankData));
    // Tsrv.utils.md5(JSON.stringify(newLayoutInfo))
  }

  private handleAdd(): void {
    const filter = {
      // initSearch?: ifs.I_fv[] | ifs.I_filter;
      // initSearch: [
      //   { field: Tsrv.globalVar.fieldName.masterBillId, value: this.processId }
      // ] as ifs.I_fv[]
      initSearch: new ts.T_filter()
    };
    const _f = { master_bill_id: { $in: [this.processId] } };

    // 如果是 “大件工艺”{craftType === 1} 且是 “硫酸阳极化工艺”{this.processId = 585792551996166144}  不能选择 “12槽”
    if (
      this.config.craftType === 1 &&
      this.processId === '585792551996166144'
    ) {
      _f['physical_slot'] = { $nin: [12] };
    }

    filter.initSearch.filter = _f;
    Tsrv.utils
      .createModal('oMagicBox', {
        source: {
          field: 'process_tank',
          filter,
          limit: 9999
        },
        config: {
          isFunLayout: false
        }
      })
      .then(data => {
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            const el = data[i];
            if (
              this.tableData.findIndex(
                it => it.tankName === el['process_tank_num']
              ) === -1
            ) {
              this.tableData.push({
                id: Tsrv.getSnowIDFmtStr(),
                tankId: el.id,
                tankName: el['f_name'],
                tankNumber: el['process_tank_num']
              });
            }
          }
        }
      });
  }

  private handleDelete(index: number): void {
    this.tableData.splice(index, 1);
  }

  private handleSubmit(): void {
    if (!this.currentNode) return;

    this.save().then((resp: Array<any>) => {
      let flag = true;
      if (resp.length === 0) {
        flag = false;
      } else {
        resp.forEach(el => {
          !el && (flag = false);
        });
      }
      // const validData = this.tableData.filter(
      //   item => item.tankName?.trim() || item.tankNumber?.trim()
      // );
      if (flag) {
        const validData = this.tableData.filter(item => item.id !== '');

        const data = this.currentNode.getData() as ProcessNodeData;
        data.tankData = JSON.parse(JSON.stringify(validData));
        this.currentNode.setData({ ...data });

        this.currentNode.setAttrs({
          tankIcon: {
            html: `<i class="ivu-icon ivu-icon-md-cube" style="font-size: 16px; color: ${
              validData.length ? '#1890ff' : '#999'
            }; cursor: pointer;" data-icon="tank"></i>`
          }
        });
      }
      // this.$bus.$emit(`modal_${this.id}`, []);
      this.handleCancel();
    });
  }

  private handleCancel(): void {
    this.hide();
    this.currentNode = null;
    this.tableData = [];
  }

  private save(): Promise<any> {
    const insertRecords = [];
    const removeRecords = [];

    if (this.originData.length === 0) {
      if (this.tableData.length > 0) {
        // insertRecords.push(...this.tableData.filter(item => item.tankName?.trim() || item.tankNumber?.trim()));
        insertRecords.push(...this.tableData.filter(item => item.id !== ''));
      }
    } else {
      this.originData.forEach(item => {
        const index = this.tableData.findIndex(it => it.id === item.id);
        if (index === -1) {
          removeRecords.push(item);
        }
      });
      this.tableData.forEach(item => {
        const index = this.originData.findIndex(it => it.id === item.id);
        if (index === -1) {
          insertRecords.push(item);
        }
      });
    }
    const removeIds = removeRecords.map(item => item.id);
    const inserts: ifs.I_baseData[] = [];
    insertRecords.forEach(item => {
      const rows = [
        new ts.T_fv().setField('id').setValue(item.id),
        new ts.T_fv().setField('master_bill_id').setValue(this.parentId),
        new ts.T_fv().setField('process_tank_id').setValue(item.tankId)
      ] as ifs.I_fv[];
      const bData = new ts.T_baseData();
      bData
        .setDataRule({} as ifs.I_rule)
        .setFileInfo({})
        .setRowData(...(rows as ifs.I_fv[]));
      inserts.push(bData);
    });
    // if (removeIds.length > 0) {
    //   this.deleteData('process_tank', removeIds)
    // }
    // if (inserts.length > 0) {
    //   this.insertData('process_tank', inserts)
    // }

    const primises = [];
    removeIds.length > 0 &&
      primises.push(this.deleteData('process_specified_slot', removeIds));
    inserts.length > 0 &&
      primises.push(this.insertData('process_specified_slot', inserts));
    if (this.parentId) {
      return Promise.all(primises);
    }
    return Promise.all([]);
  }

  // 插入数据
  public insertData(
    tableName: string,
    insertRecords: ifs.I_baseData[]
  ): Promise<any> {
    const that = this;
    return new Promise(resolve => {
      const ctd = new ts.T_ctdArg();
      ctd
        .setTableName(tableName)
        .setDbType(Tsrv.globalVar.dbType.MYSQL)
        .setRule({} as ifs.I_rule);
      const scope = {};
      // const insertRecords: ifs.I_baseData[] = [];
      // const bData = new ts.T_baseData();
      // bData
      //   .setDataRule({} as ifs.I_rule)
      //   .setFileInfo({})
      //   .setRowData(...(rows as ifs.I_fv[]));
      // insertRecords.push(bData);
      ctd.setInsRecDataMany(scope, ...insertRecords);
      Tsrv.batRows(ctd).then(resp => {
        const [b, res, msg] = resp;
        msg && that.$msg(msg);
        // msg && Vue.prototype.$msg(msg);
        if (b) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    });
  }

  public deleteData(tableName: string, removeRecords: string[]): Promise<any> {
    const that = this;
    return new Promise(resolve => {
      const ctd = new ts.T_ctdArg();
      ctd.setTableName(tableName).setDbType(Tsrv.globalVar.dbType.MYSQL);
      ctd.setRule({} as ifs.I_rule);
      const ids = `"${removeRecords.join(`","`)}"`;
      const filter = JSON.parse(`{"id":{"$in":[${ids}]}}`);
      ctd.setDelRecData({} as ifs.I_rule, filter);
      Tsrv.batRows(ctd).then(resp => {
        const [b, res, msg] = resp;
        msg && that.$msg(msg);
        if (b) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    });
  }

  public show() {
    const that = this;
    this.showAnimation = {
      display: 'block',
      // 'z-index': 102 + this.id
      'z-index': 202 + this.id
    };
    setTimeout(() => {
      that.showAnimation = {
        display: 'block',
        opacity: 1,
        // 'z-index': 102 + this.id
        'z-index': 202 + this.id
      };
    }, 10);
  }

  public hide() {
    const that = this;
    this.showAnimation = {
      display: 'block',
      opacity: 0,
      // 'z-index': 102 + this.id
      'z-index': 202 + this.id
    };
    setTimeout(() => {
      that.showAnimation = {
        display: 'none',
        // 'z-index': 102 + this.id
        'z-index': 202 + this.id
      };
      this.$bus.$emit(`modal_${this.id}`, null);
    }, 200);
  }
}
</script>

<style lang="less" scoped>
.tank-dialog {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  display: none;
  transition: ease-in-out 0.2s;
  .back {
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100%;
  }
  .front {
    position: absolute;
    max-width: 560px;
    min-height: 150px;
    overflow: hidden;
    top: 30%;
    left: 50%;
    width: calc(100% - 30px);
    // height: calc(100% - 30px);
    transform: translate(-50%, -50%);
    border-radius: 10px;
    background-color: #fefcfa;
    box-shadow: 0px 50px 100px 15px #a1a1b3;

    .modal-header {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      background-color: rgb(247, 247, 247);
      padding: 0 20px;
      .mdoal-title {
        font-size: 14px;
        font-weight: 700;
      }
    }

    .modal-footer {
      width: 100%;
      height: 45px;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      .modal-button {
        width: calc(50% - 1px);
        transition: all 250ms ease-in-out;
        // background-color: #fdf3e9;
        background-color: #57a3f340;
        color: #818994;
        line-height: 45px;
        overflow: hidden;
        position: relative;
        text-align: center;
        text-decoration: none;
        text-transform: uppercase;

        &:before {
          content: attr(data-text);
          position: relative;
          z-index: 2;
        }

        &:after {
          transition: top 250ms ease-in-out;
          // background-color: darken(#fdf3e9, 5%);
          background-color: #2d8eff;
          content: '';
          height: 100%;
          left: 0%;
          position: absolute;
          top: 100%;
          width: 100%;
          z-index: 1;
        }

        &:hover {
          color: #fefcfa;
          &:after {
            top: 0;
          }
        }
      }

      &:first-child {
        border-right: 1px solid #fefcfa;
      }

      &:last-child {
        border-left: 1px solid #fefcfa;
      }
    }
  }
}
</style>
